import os
import sys
import datetime
import pickle
import glob

DATABASE_PATH = './data/'

def create_dir_if_not_exists (path) :
    if os.path.isdir(path) == False:
        os.mkdir(path)
        return True
    return False

class CodeSnippet:
    _id = ''
    _title = ''
    _code = ''
    _author = ''
    _datetime = None
    _visible = True
    def __init__(self, title, code, author, datetime=None, cid='', visible=True):
        self._title = title
        self._code = code
        self._author = author
        self._id = cid
        self._datetime = datetime
        #_datetime = datetime.datetime.now()
    def save(self):
        if self._author is not '':
            path = DATABASE_PATH + self._author + '/'
            create_dir_if_not_exists(path)
            if self._id is '':
                file_id = str(len(glob.glob(path + '*.codesnippet')))
                self._id = file_id
            fp = open(path + self._id + '.codesnippet', 'w')
            content = pickle.dumps({'id' : self._id,
                                    'visible' : self._visible,
                                    'title':self._title, 
                                    'code':self._code, 
                                    'author':self._author, 
                                    'date':str(datetime.datetime.now())})
            fp.write(content)
            fp.close()
            return True

def get_snippet_names_by_author(author):
    path = DATABASE_PATH + author + '/'
    files = glob.glob(path + '*.codesnippet')
    return files
    
def get_snippet_by_file(path):
    f = open(path, 'r')
    line = f.readline()
    content = ''
    while line !='' : 
        content += line
        line = f.readline()
    ret = pickle.loads(content)
    return ret

if __name__ == '__main__':
    c = CodeSnippet('title', 'print hello', 'test')
    c.save()

